package com.gzedu.common.sys;

import java.io.Serializable;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gzedu.common.util.MD5Utils;
import com.gzedu.module.faced.user.UserFaced;
import com.gzedu.module.modle.user.User;
import com.gzedu.module.utils.UserUtils;

public class SystemAuthorizingRealm extends AuthorizingRealm {

	@Autowired
	private UserFaced userFaced;
	

	@Override

	protected AuthorizationInfo doGetAuthorizationInfo(

			PrincipalCollection principals) {

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

		info.addStringPermission("sys:manager");

		info.addStringPermission("user");

		System.out.println("开始授权");

		return info;

	}

	@Override

	protected AuthenticationInfo doGetAuthenticationInfo(

			AuthenticationToken token) throws AuthenticationException {

		UsernamePasswordToken upToken = (UsernamePasswordToken) token;

		String username = upToken.getUsername();

		String password = new String(upToken.getPassword());
		password = MD5Utils.getPwd(password);

		User user = userFaced.getUserByName(username);

		System.out.println("===========");

		if (user != null) {

			if (user.getPassword().equals(password)) {

				return new SimpleAuthenticationInfo(username, password, getName());

			}

		}

		throw new UnauthenticatedException();

	}

	public static class Principal implements Serializable {

		private static final long serialVersionUID = 1L;

		private String id; // 编号

		private String loginName; // 登录名

		private String name; // 姓名

		public Principal(User user) {

			this.id = user.getId();

			this.loginName = user.getUserName();

			this.name = user.getName();

		}


		public String getId() {
			return id;
		}





		public String getLoginName() {

			return loginName;

		}

		public String getName() {

			return name;

		}

		/**
		 * 
		 * 获取SESSIONID
		 * 
		 */

		public String getSessionid() {

			try {

				return (String) UserUtils.getSession().getId();

			} catch (Exception e) {

				return "";

			}

		}


	}

}